<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>重置密码 - SnapAn</title>
  <style>
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
      font-family: 'Segoe UI', 'Microsoft YaHei', sans-serif;
    }

    body {
      background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%);
      display: flex;
      justify-content: center;
      align-items: center;
      min-height: 100vh;
      padding: 20px;
    }

    .reset-container {
      background-color: white;
      border-radius: 12px;
      box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
      width: 100%;
      max-width: 450px;
      padding: 40px 35px;
      position: relative;
      overflow: hidden;
      animation: fadeIn 0.5s ease-out;
    }

    .reset-container::before {
      content: '';
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 5px;
      background: linear-gradient(to right, #6a11cb, #2575fc);
    }

    @keyframes fadeIn {
      from { opacity: 0; transform: translateY(20px); }
      to { opacity: 1; transform: translateY(0); }
    }

    h1 {
      text-align: center;
      margin-bottom: 30px;
      color: #333;
      font-weight: 600;
      font-size: 28px;
    }

    .input-group {
      margin-bottom: 20px;
      position: relative;
    }

    label {
      display: block;
      margin-bottom: 8px;
      color: #555;
      font-weight: 500;
      font-size: 14px;
    }

    input[type="email"],
    input[type="password"],
    input[type="text"] {
      width: 100%;
      padding: 14px 15px;
      border: 1px solid #ddd;
      border-radius: 8px;
      font-size: 16px;
      transition: all 0.3s;
      height: 48px; /* 统一高度 */
    }

    input[type="email"]:focus,
    input[type="password"]:focus,
    input[type="text"]:focus {
      border-color: #6a11cb;
      box-shadow: 0 0 0 2px rgba(106, 17, 203, 0.2);
      outline: none;
    }

    .input-error {
      border-color: #ff4757 !important;
      box-shadow: 0 0 0 2px rgba(255, 71, 87, 0.2) !important;
    }

    .error-message {
      color: #ff4757;
      font-size: 12px;
      margin-top: 5px;
      display: none;
    }

    .captcha-group {
      display: flex;
      gap: 10px;
    }

    .captcha-input {
      flex: 1;
    }

    .captcha-btn {
      padding: 0 20px;
      background: linear-gradient(to right, #6a11cb, #2575fc);
      color: white;
      border: none;
      border-radius: 8px;
      cursor: pointer;
      font-size: 14px;
      transition: all 0.3s;
      white-space: nowrap;
      height: 48px; /* 与输入框高度一致 */
      min-width: 120px; /* 确保按钮有足够宽度 */
    }

    .captcha-btn:hover {
      opacity: 0.9;
    }

    .captcha-btn:disabled {
      background: #ccc;
      cursor: not-allowed;
    }

    .reset-btn {
      width: 100%;
      padding: 14px;
      background: linear-gradient(to right, #6a11cb, #2575fc);
      color: white;
      border: none;
      border-radius: 8px;
      font-size: 16px;
      font-weight: 600;
      cursor: pointer;
      transition: transform 0.2s, box-shadow 0.2s;
      margin-bottom: 25px;
      height: 48px; /* 保持一致性 */
    }

    .reset-btn:hover {
      transform: translateY(-2px);
      box-shadow: 0 5px 15px rgba(106, 17, 203, 0.4);
    }

    .reset-btn:active {
      transform: translateY(0);
    }

    .login-link {
      text-align: center;
      color: #666;
      font-size: 14px;
    }

    .login-link a {
      color: #6a11cb;
      text-decoration: none;
      font-weight: 500;
      transition: color 0.2s;
    }

    .login-link a:hover {
      color: #2575fc;
      text-decoration: underline;
    }

    @media (max-width: 480px) {
      .reset-container {
        padding: 30px 25px;
      }

      h1 {
        font-size: 24px;
      }

      .captcha-group {
        flex-direction: column;
      }

      .captcha-btn {
        padding: 12px;
        margin-top: 10px;
        height: 48px; /* 移动端保持高度一致 */
      }
    }

    .success-message {
      display: none;
      background-color: #2ed573;
      color: white;
      padding: 12px;
      border-radius: 8px;
      text-align: center;
      margin-bottom: 20px;
    }
  </style>
</head>
<body>
<div class="reset-container">
  <h1>重置密码</h1>

  <div class="success-message" id="successMessage">
    密码重置成功！正在跳转到登录页面...
  </div>

  <form id="resetForm" action="reset" method="post">
    <div class="input-group">
      <label for="email">账号（邮箱）</label>
      <input type="email" id="email" name="email" placeholder="请输入您的邮箱" required>
      <div class="error-message" id="emailError">请输入有效的邮箱地址</div>
    </div>


    <div class="input-group">
      <label for="captcha">验证码</label>
      <div class="captcha-group">
        <input type="text" id="captcha" name="captcha" class="captcha-input" placeholder="请输入验证码" required>
        <button type="button" class="captcha-btn" id="getCaptcha">获取验证码</button>
      </div>
      <div class="error-message" id="captchaError">请输入正确的验证码</div>
    </div>

    <div class="input-group">
      <label for="newPassword">新密码</label>
      <input type="password" id="newPassword" name="newPassword" placeholder="请输入新密码" required>
      <div class="error-message" id="newPasswordError">密码长度至少8位，包含字母和数字</div>
    </div>

    <div class="input-group">
      <label for="confirmPassword">确认新密码</label>
      <input type="password" id="confirmPassword" name="confirmPassword" placeholder="请再次输入新密码" required>
      <div class="error-message" id="confirmPasswordError">两次输入的密码不一致</div>
    </div>

    <button type="submit" class="reset-btn">确定</button>
  </form>

  <div class="login-link">
    想起密码了？<a href="/login">返回登录</a>
  </div>
</div>

<script>
  // 获取DOM元素
  const resetForm = document.getElementById('resetForm');
  const emailInput = document.getElementById('email');
  const newPasswordInput = document.getElementById('newPassword');
  const confirmPasswordInput = document.getElementById('confirmPassword');
  const captchaInput = document.getElementById('captcha');
  const getCaptchaBtn = document.getElementById('getCaptcha');
  const successMessage = document.getElementById('successMessage');

  // 验证正则规则
  const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; // 邮箱格式
  const PASSWORD_REGEX = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/; // 密码：8位+字母+数字

  /**
   * 显示错误信息
   * @param {HTMLElement} inputElement - 输入框元素
   * @param {string} message - 错误提示内容
   */
  function showError(inputElement, message) {
    const errorElement = document.getElementById(inputElement.id + 'Error');
    inputElement.classList.add('input-error');
    errorElement.textContent = message;
    errorElement.style.display = 'block';
  }

  /**
   * 清除错误信息
   * @param {HTMLElement} inputElement - 输入框元素
   */
  function clearError(inputElement) {
    const errorElement = document.getElementById(inputElement.id + 'Error');
    inputElement.classList.remove('input-error');
    errorElement.style.display = 'none';
  }

  /**
   * 验证单个输入字段
   * @param {HTMLElement} inputElement - 输入框元素
   * @returns {boolean} - 验证结果（true为通过）
   */
  function validateField(inputElement) {
    const value = inputElement.value.trim();

    // 通用非空验证
    if (!value) {
      showError(inputElement, '此字段不能为空');
      return false;
    }

    // 按字段类型/ID差异化验证
    switch (inputElement.id) {
      case 'email':
        // 邮箱格式验证
        if (!EMAIL_REGEX.test(value)) {
          showError(inputElement, '请输入有效的邮箱地址');
          return false;
        }
        break;
      // case 'confirmEmail':
        // 确认邮箱与原邮箱一致性验证
        const email = emailInput.value.trim();
        if (value !== email) {
          showError(inputElement, '两次输入的邮箱不一致');
          return false;
        }
        break;
      case 'newPassword':
        // 密码强度验证
        if (!PASSWORD_REGEX.test(value)) {
          showError(inputElement, '密码长度至少8位，包含字母和数字');
          return false;
        }
        break;
      case 'confirmPassword':
        // 确认密码与原密码一致性验证
        const password = newPasswordInput.value.trim();
        if (value !== password) {
          showError(inputElement, '两次输入的密码不一致');
          return false;
        }
        break;
      case 'captcha':
        // 验证码非空及长度验证
        if (value.length !== 6) {
          showError(inputElement, '验证码需为6位字符');
          return false;
        }
        break;
    }

    clearError(inputElement);
    return true;
  }

  /**
   * 发送重置密码验证码（对接新的后端接口）
   * @param {string} email - 目标邮箱
   * @returns {Promise<Object>} - 接口响应结果
   */
  async function sendResetCode(email) {
    try {
      const response = await fetch('/api/verification/send', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: new URLSearchParams({
          email: email,
          type: '2' // 重置密码类型，对应后端的Byte类型2
        })
      });

      const result = await response.json();
      return result; // 后端返回格式：{success: true/false, message: "提示信息"}
    } catch (error) {
      console.error('发送验证码失败:', error);
      return { success: false, message: '网络异常，请稍后重试' };
    }
  }
  /**
   * 验证重置密码验证码（对接新的后端接口）
   * @param {string} email - 目标邮箱
   * @param {string} code - 用户输入的验证码
   * @returns {Promise<boolean>} - 验证结果（true为通过）
   */
  async function verifyResetCode(email, code) {
    try {
      const response = await fetch('/api/verification/verify', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: new URLSearchParams({
          email: email,
          code: code,
          type: '2' // 重置密码类型
        })
      });

      const result = await response.json();
      if (!result.success) {
        // 验证码错误时，显示后端返回的提示
        showError(captchaInput, result.message);
        return false;
      }
      return true;
    } catch (error) {
      console.error('验证验证码失败:', error);
      showError(captchaInput, '网络异常，验证失败');
      return false;
    }
  }
  /**
   * 提交重置密码表单（适配后端返回纯字符串）
   * @param {FormData} formData - 表单数据
   * @returns {Promise<Object>} - 接口响应结果
   */
  async function submitResetForm(formData) {
    try {
      const response = await fetch('/api/user/update-password', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: new URLSearchParams({
          email: formData.get('email'),
          newPassword: formData.get('newPassword')
        })
      });

      // 后端返回的是纯字符串，不是JSON
      const resultText = await response.text();

      // 根据HTTP状态码判断成功与否
      if (response.ok) {
        return { success: true, message: resultText };
      } else {
        return { success: false, message: resultText || '重置密码失败' };
      }
    } catch (error) {
      console.error('重置密码请求失败:', error);
      return { success: false, message: '网络异常，重置失败' };
    }
  }

  /**
   * 验证码倒计时功能（防止重复发送）
   * @param {HTMLButtonElement} button - 验证码按钮元素
   * @param {number} countdownSeconds - 倒计时秒数（默认60秒）
   */
  function startCountdown(button, countdownSeconds = 60) {
    let countdown = countdownSeconds;
    button.disabled = true;
    button.textContent = `重新发送(${countdown}s)`;

    const timer = setInterval(() => {
      countdown--;
      button.textContent = `重新发送(${countdown}s)`;

      if (countdown <= 0) {
        clearInterval(timer);
        button.disabled = false;
        button.textContent = '获取验证码';
      }
    }, 1000);
  }

  // 修复输入框验证选择器（删除不存在的 confirmEmail）
  document.querySelectorAll('#email, #newPassword, #confirmPassword, #captcha').forEach(input => {
    input.addEventListener('blur', () => validateField(input));
    input.addEventListener('input', () => clearError(input));
  });

  // 「获取验证码」按钮点击事件
  getCaptchaBtn.addEventListener('click', async function () {
    const email = emailInput.value.trim();
    const button = this;

    // 先验证邮箱格式
    if (!validateField(emailInput)) {
      return;
    }

    // 禁用按钮，防止重复点击
    button.disabled = true;
    button.textContent = '发送中...';

    // 调用发送验证码接口
    const sendResult = await sendResetCode(email);

    if (sendResult.success) {
      // 发送成功：启动倒计时，提示用户
      alert(sendResult.message);
      startCountdown(button);
    } else {
      // 发送失败：恢复按钮，显示错误
      alert(sendResult.message);
      button.disabled = false;
      button.textContent = '获取验证码';
    }
  });

  // 重置密码表单提交事件
  resetForm.addEventListener('submit', async function (e) {
    e.preventDefault();

    // 步骤1：验证所有表单字段
    const formFields = [emailInput, newPasswordInput, confirmPasswordInput, captchaInput];
    let isFormValid = true;

    formFields.forEach(field => {
      if (!validateField(field)) {
        isFormValid = false;
      }
    });

    if (!isFormValid) {
      return;
    }

    // 步骤2：验证验证码
    const email = emailInput.value.trim();
    const captcha = captchaInput.value.trim();
    const isCodeValid = await verifyResetCode(email, captcha);

    if (!isCodeValid) {
      return;
    }

    // 步骤3：准备表单数据
    const formData = new FormData(resetForm);
    formData.delete('confirmPassword');

    // 步骤4：禁用重置按钮
    const resetBtn = this.querySelector('.reset-btn');
    resetBtn.disabled = true;
    resetBtn.textContent = '处理中...';

    // 步骤5：提交重置密码请求
    const resetResult = await submitResetForm(formData);

    // 步骤6：处理重置结果
    if (resetResult.success) {
      // 重置成功：显示成功提示，跳转登录页
      successMessage.style.display = 'block';
      resetForm.style.display = 'none';

      setTimeout(() => {
        window.location.href = '/login';
      }, 2000);
    } else {
      // 重置失败：恢复按钮，提示错误
      alert(resetResult.message);
      resetBtn.disabled = false;
      resetBtn.textContent = '确定';
    }
  });</script>
</body>
</html>